/*
 * Copyright Aduna (http://www.aduna-software.com/) (c) 1997-2007.
 *
 * Licensed under the Aduna BSD-style license.
 */
package edu.tju.commons.collections;

import java.util.Collection;
import java.util.LinkedList;

/**
 * @author Herko ter Horst
 */
public class FixedSizeQueue<E> extends LinkedList<E> {
	private static final long serialVersionUID = 1L;

	private int m_maxSize = Integer.MAX_VALUE;

	public FixedSizeQueue(int maxSize) {
		m_maxSize = maxSize;
	}

	public FixedSizeQueue(int maxSize, Collection<? extends E> c) {
		super(c);
		setMaxSize(maxSize);
	}

	public void setMaxSize(int maxSize) {
		m_maxSize = maxSize;
		enforceMaxSize();
	}

	public int getMaxSize() {
		return m_maxSize;
	}

	private void enforceMaxSize() {
		if (size() > getMaxSize()) {
			removeRange(0, size() - m_maxSize);
		}
	}

	@Override
	public boolean add(E o) {
		boolean result = super.add(o);
		enforceMaxSize();
		return result;
	}

	@Override
	public void add(int index, E element) {
		super.add(index, element);
		enforceMaxSize();
	}

	@Override
	public boolean addAll(Collection<? extends E> c) {
		boolean result = super.addAll(c);
		enforceMaxSize();
		return result;
	}

	@Override
	public boolean addAll(int index, Collection<? extends E> c) {
		boolean result = super.addAll(index, c);
		enforceMaxSize();
		return result;
	}

	@Override
	public void addFirst(E o) {
		super.addFirst(o);
		enforceMaxSize();
	}

	@Override
	public void addLast(E o) {
		super.addLast(o);
		enforceMaxSize();
	}
}
